package com.ufaud.ais.sys.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.dao.DataAccessException;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsService;
import org.springframework.security.userdetails.UsernameNotFoundException;

import com.ufaud.ais.pub.dao.IGenericCRUDDao;
import com.ufaud.ais.sys.entity.Employee;
import com.ufaud.ais.sys.view.EmployeeView;

public class SecurityServiceImpl implements UserDetailsService{
	
	private IGenericCRUDDao<Employee, Long> employeeDao;

	public SecurityServiceImpl(IGenericCRUDDao<Employee, Long> employeeDao) {
		this.employeeDao = employeeDao;
	}

	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {
		Map<String, Object> queryParams = new HashMap<String, Object>();
		queryParams.put("username", username);
		List<Employee> list = employeeDao.findByNamedQuery("findUserByName", queryParams);
		if(list == null || list.size() == 0)
			throw new UsernameNotFoundException(username);
		else {
			Employee curUser = list.get(0);
			EmployeeView employeeView = new EmployeeView(curUser);
			employeeView.setDepartment(curUser.getDepartment());
			employeeView.setRoleSet(curUser.getRoleSet());
			return employeeView;
		}
	}
	
	// TODO 可能加入基于数据库的角色-资源授权支持

}
